import {messages,queryCurrencyPrecision} from "share/common";
import React from 'react'
import { connect } from 'react-redux'
import { Form, Input, Button, Select, Spin, Row, Col, InputNumber, message } from 'antd'
const FormItem = Form.Item;
const Option = Select.Option;
const TextArea = Input.TextArea;

import loanAndRefundService from 'containers/financial-management/loan-and-refund/loan-and-refund.service'
import LPService from 'containers/enterprise-manage/legal-person/legal-person.service'
import ImageUpload from 'components/image-upload'
import Chooser from 'components/chooser'
import 'styles/request/loan-request/new-repayment-frame.scss'

class NewPaymentFrame extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      accountFetching: false,
      accountOptions: [],
      companyOption: [],
      companyBankOption: [],
      bankSpin: false,
      acceptAccountName: undefined,
      acceptAccount: undefined,
      acceptBankName: undefined,
      repayAttchment: [],
      repayAttchmentImages: [],
      currency: null,
      amount: 0,
      isEditBankInfo:true,
      info: {},
      myBankInfo: {},
      loanRefund: false,
      paymentType: 'cash', //付款方式
    }
  }

  componentDidMount() {
    this.getAcceptAccount()
  }

  componentWillReceiveProps(nextProps) {
    if(!nextProps.params.hasInit) {
      nextProps.params.hasInit = true;
      this.setState({
        currency: nextProps.params.info ? nextProps.params.info.originCurrencyCode : "",//原币种
        amount: nextProps.params.amount,
        info: nextProps.params.info || {},
        loanRefund: nextProps.params.loanRefund,
        paymentType: this.props.profile['finance.cash.repaymemt.disabled'] ? 'card' : 'cash',
        acceptAccount: this.state.accountOptions[0] ? this.state.accountOptions[0].cardNumber : undefined,
        acceptBankName: this.state.accountOptions[0] ? this.state.accountOptions[0].accountBank : undefined,
        repayAttchment: [],
        repayAttchmentImages: [],
      },() => {
        loanAndRefundService.getCompanyBank({page: 0, size: 100, companyOID: this.state.info.companyOID}).then(res => {
          this.setState({companyBankOption: res.data});
        });
        !this.state.myBankInfo.bankAccountNo && this.getBankInfo();
        this.props.form.resetFields()
      })
    }
  }

  //获取还款用户的默认账户信息
  getBankInfo = () => {
    let {info, isEditBankInfo}=this.state;
    this.state.info.applicant && loanAndRefundService.getAccountBankInfo(info.applicationOID, info.applicant.userOID).then(res => {
      res.data.map(item => {
        if(item.isPrimary){
          isEditBankInfo = !!item.userOID;
          this.setState({ myBankInfo: item || {},isEditBankInfo })
        }
      })
    })
  };

  handlePaymentTypeChange = (value) => {
    this.setState({ paymentType: value },() => {
      const { isOldCompany } = this.props;
      const { myBankInfo, info, accountOptions } = this.state;
      this.props.form.setFieldsValue({
        payAccountName: myBankInfo.bankAccountName || info.applicant.fullName,
        payAccount: myBankInfo.bankAccountNo,
        payBankName: myBankInfo.bankCode ? [{bankCode: myBankInfo.bankCode, bankBranchName: myBankInfo.branchName}] : undefined,
        remark: undefined,
        acceptAccountName: isOldCompany ? accountOptions[0].companyName : info.companyOID,
        acceptAccount: isOldCompany ? accountOptions[0].cardNumber : undefined,
        acceptBankName: isOldCompany ? accountOptions[0].accountBank : undefined
      })
    })
  };

  //获取收款方信息
  getAcceptAccount = () => {
    this.setState({ accountFetching: true });
    const { isOldCompany } = this.props;
    if(isOldCompany){
      LPService.getLegalList({page: 0, size: 100}).then(res => {
        this.setState({
          accountFetching: false,
          accountOptions: res.data,
          acceptAccount: res.data[0].cardNumber,
          acceptBankName: res.data[0].accountBank
        })
      }).catch(() => {
        this.setState({ accountFetching: false })
      })
    }else{
      loanAndRefundService.getCompany({page: 0, size: 100}).then(res => {
        this.setState({
          accountFetching: false,
          companyOption: res.data,
          acceptAccount: '',
          acceptBankName: '',
        })
      }).catch(() => {
        this.setState({accountFetching: false});
      })
    }
  };

  onChangeAcceptAccount = (id) => {
    const { isOldCompany } = this.props;
    if(isOldCompany){
      this.state.accountOptions.map(item => {
        if(item.id === id) {
          this.setState({
            acceptAccountName: item.companyName,
            acceptAccount: item.cardNumber,
            acceptBankName: item.accountBank
          }, () => {
            this.props.form.setFieldsValue({
              acceptAccountName: this.state.acceptAccountName,
              acceptAccount: this.state.acceptAccount,
              acceptBankName: this.state.acceptBankName
            })
          })
        }
      })
    }else {
      this.setState({bankSpin : true});
      loanAndRefundService.getCompanyBank({page: 0, size: 100, companyOID: id}).then(res => {
        this.setState({
          bankSpin: false,
          companyBankOption: res.data,
          acceptAccountName: this.state.companyOption.filter(item => item.companyOID === id)[0].name,
          acceptAccount: undefined,
          acceptBankName: undefined
        },() => {
          this.props.form.setFieldsValue({
            acceptAccount: this.state.acceptAccount,
            acceptBankName: this.state.acceptBankName
          })
        })
      }).catch(() => {
        this.setState({
          bankSpin: false,
          companyBankOption: [],
          acceptAccountName: this.state.companyOption.filter(item => item.companyOID === id)[0].name,
          acceptAccount: undefined,
          acceptBankName: undefined
        },() => {
          this.props.form.setFieldsValue({
            acceptAccount: this.state.acceptAccount,
            acceptBankName: this.state.acceptBankName
          })
        });
      })
    }
  };

  handleChangeAcceptAccount = (id) => {
    const { companyBankOption } = this.state;
    companyBankOption.map(item => {
      if(item.bankAccountNumber === id){
        this.setState({
          acceptBankName: item.bankName,
          acceptAccount: id
        },() => {
          this.props.form.setFieldsValue({
            acceptAccount: this.state.acceptAccount,
            acceptBankName: this.state.acceptBankName
          })
        })
      }
    })
  };

  //获取上传图片的OId
  getUploadImageOId = (values) => {
    let repayAttchment = [];
    values.map(item => {
      repayAttchment.push({attachmentOID: item.attachmentOID})
    });
    this.setState({ repayAttchment, repayAttchmentImages: values })
  };

  handleSave = (e) => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if(!err) {
        const { info, repayAttchment, paymentType, loanRefund, acceptAccountName, accountOptions } = this.state;
        const { isOldCompany } = this.props;
        values.loanApplicationOid = info.applicationOID;
        values.repayAttchment = repayAttchment;
        loanRefund && (values.isFinance = true);
        values.payBankName && (values.payBankName = values.payBankName[0].bankBranchName);
        values.paymentType === 'card' && (values.acceptAccountName = acceptAccountName || (isOldCompany ? accountOptions[0].companyName : info.companyName));
        this.setState({ loading: true });
        let method = paymentType === 'cash' ? 'cashRepayment' : 'cardRepayment';
        loanAndRefundService[method](values).then(() => {
          this.setState({ loading: false });
          message.success(messages('common.operate.success'));
          this.props.close(true)
        }).catch(e => {
          this.setState({ loading: false });
          message.error(`${messages('common.operate.filed')}，${e.response.data.message}`)
        })
      }
    })
  };

  handleCancel = () => {
    this.props.close()
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    const { loading, accountFetching, accountOptions, acceptAccount, acceptBankName, currency, amount, info, paymentType,
      loanRefund, myBankInfo, isEditBankInfo, repayAttchmentImages, companyOption, companyBankOption, bankSpin } = this.state;
    let applicant = info.applicant || {}; //申请人信息
    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 14, offset: 1 }
    };
    let currencyPrecision = queryCurrencyPrecision(currency);
    return (
      <div className="new-repayment-frame">
        <Form onSubmit={this.handleSave}>
          <h4 className="title">{messages('request.key135'/*还款方信息*/)}</h4>
          {loanRefund && (
            <div>
              <FormItem {...formItemLayout} label={messages('request.key136'/*姓名*/)} style={{marginBottom:20}}>
                <div>{applicant.fullName}</div>
              </FormItem>
              <FormItem {...formItemLayout} label={messages('request.key4'/*部门*/)}>
                <div>{info.departmentName || '-'}</div>
              </FormItem>
            </div>
          )}
          <Row>
            <Col span={6} className="form-define-title required">{messages('request.key131'/*还款金额*/)}：</Col>
            <Col span={3} offset={1}><FormItem>{getFieldDecorator('curreny', {
              initialValue: currency
            })(<Input disabled/>)}</FormItem></Col>
            <Col span={5}>
              <FormItem>
                {getFieldDecorator('repaymentValue', {
                  rules: [{
                    required: true,
                    message: messages('common.please.enter')
                  }, {
                    pattern: /[1-9]/,
                    message: messages('request.key137'/*还款金额要大于 0*/)
                  }],
                  initialValue: this.filterMoney(amount,currencyPrecision,true).replace(/,/mg,'')
                })(
                  <InputNumber min={0} max={this.filterMoney(amount,currencyPrecision,true)} precision={currencyPrecision} className="input-number"
                               disabled={!loanRefund}/>
                )}
              </FormItem>
            </Col>
          </Row>
          <FormItem {...formItemLayout} label={messages('request.key125'/*还款方式*/)}>
            {getFieldDecorator('paymentType', {
              rules: [{
                required: true,
                message: messages('common.please.enter')
              }],
              initialValue: paymentType
            })(
              <Select onChange={this.handlePaymentTypeChange} getPopupContainer={triggerNode => triggerNode.parentNode}>
                {!this.props.profile['finance.cash.repaymemt.disabled'] && (
                  <Option key='cash'>{messages('request.key127'/*现金还款*/)}</Option>
                )}
                <Option key='card'>{messages('request.key128'/*转账还款*/)}</Option>
              </Select>
            )}
          </FormItem>
          {paymentType === 'card' && (
            <div>
              <FormItem {...formItemLayout} label={messages('request.key138'/*开户名*/)}>
                {getFieldDecorator('payAccountName', {
                  rules: [{
                    required: true,
                    message: messages('common.please.enter'),
                  }],
                  initialValue: myBankInfo.bankAccountName || applicant.fullName
                })(
                  <Input disabled={!isEditBankInfo} placeholder={messages('common.please.enter')} />
                )}
              </FormItem>
              <FormItem {...formItemLayout} label={messages('request.key139'/*开户账号*/)}>
                {getFieldDecorator('payAccount', {
                  rules: [{
                    required: true,
                    message: messages('common.please.enter')
                  }],
                  initialValue: myBankInfo.bankAccountNo
                })(
                  <Input disabled={!isEditBankInfo} placeholder={messages('common.please.enter')} />
                )}
              </FormItem>
              <FormItem {...formItemLayout} label={messages('request.key140'/*开户银行*/)} className="pay-bank-container">
                {getFieldDecorator('payBankName', {
                  rules: [{
                    required: true,
                    message: messages('common.please.select')
                  }],
                  initialValue: myBankInfo.bankCode ? [{bankCode: myBankInfo.bankCode || '', bankBranchName: myBankInfo.branchName}] : undefined
                })(
                  <Chooser single={true}
                           type="select_bank"
                           placeholder={messages("common.please.select")}
                           labelKey="bankBranchName"
                           valueKey="bankCode"/>
                )}
              </FormItem>
            </div>
          )}
          {paymentType === 'card' && (
            <div>
              <FormItem {...formItemLayout} label={messages('request.key141'/*银行回单号*/)}>
                {getFieldDecorator('bankReceiptNumber', {
                  rules: [{
                    max: 50,
                    message: messages('common.max.characters.length', {max: 50})
                  }],
                })(
                  <Input/>
                )}
              </FormItem>
              <FormItem {...formItemLayout} label={`${messages('request.key142'/*流水转账凭证*/)}（${messages('common.max.image.length', {max: 3})}）`}>
                {getFieldDecorator('repayAttchment', {
                  rules: [{
                    required: !this.props.profile['ca.opt.didi.refund.upload.disabled'],
                    message: messages('common.please.select')
                  }],
                  initialValue: []
                })(
                  <ImageUpload attachmentType="REPAYMENT_IMAGES"
                               defaultFileList={repayAttchmentImages}
                               fileType={["PNG", 'png', 'JEPG', 'jepg', 'jpg', 'JPG', 'bmp', 'BMP',"jpg","JPG","jpeg","JPEG"]}
                               isShowDefault
                               maxNum={3}
                               onChange={this.getUploadImageOId}/>
                )}
              </FormItem>
            </div>
          )}
          { paymentType === 'cash'  && (
            <FormItem {...formItemLayout} label={messages('common.remark')}>
              {getFieldDecorator('remark', {
                rules: [{
                  max: 200,
                  message: messages('common.max.characters.length', {max: 200})
                }],
              })(
                <TextArea placeholder={messages('common.max.characters.length', {max: 200})} rows={3} style={{resize: 'none'}}/>
              )}
            </FormItem>
          )}
          { paymentType === 'card' && (
            <div>
              <h4 className="title">
                {messages('request.key143'/*收款方信息*/)}
                <span> {messages('request.key144'/*请按以下收款方账号打款*/)}</span>
              </h4>
              {
                this.props.isOldCompany ? (
                  <div>
                    <FormItem {...formItemLayout} label={messages('request.key138'/*开户名*/)} className="accept-account-container">
                      {getFieldDecorator('acceptAccountName', {
                        rules: [{
                          required: true,
                          message: messages('common.please.select')
                        }],
                        initialValue: accountOptions[0] && accountOptions[0].companyName
                      })(
                        <Select placeholder={messages('common.please.select')}
                                showSearch
                                allowClear
                                filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                                getPopupContainer={() => document.getElementsByClassName('accept-account-container')[0]}
                                onChange={this.onChangeAcceptAccount}
                                notFoundContent={accountFetching ? <Spin size="small" /> : messages('request.key145'/*无匹配结果*/)}>
                          {accountOptions.map(option => {
                            return <Option key={option.id}>{option.companyName}</Option>
                          })}
                        </Select>
                      )}
                    </FormItem>
                    <FormItem {...formItemLayout} label={messages('request.key139'/*开户账号*/)}>
                      {getFieldDecorator('acceptAccount', {
                        initialValue: acceptAccount
                      })(
                        <Input disabled/>
                      )}
                    </FormItem>
                  </div>
                ) : (
                  <div>
                    <FormItem {...formItemLayout} label={messages('request.key138'/*开户名*/)} className="accept-account-container">
                      {getFieldDecorator('acceptAccountName', {
                        rules: [{
                          required: true,
                          message: messages('common.please.select')
                        }],
                        // 取单据上的公司oid
                        initialValue: info.companyOID
                      })(
                        <Select placeholder={messages('common.please.select')}
                                showSearch
                                allowClear
                                getPopupContainer={() => document.getElementsByClassName('accept-account-container')[0]}
                                onChange={this.onChangeAcceptAccount}
                                notFoundContent={accountFetching ? <Spin size="small" /> : messages('request.key145'/*无匹配结果*/)}>
                          {companyOption.map(option => {
                            return <Option key={option.companyOID}>{option.name}</Option>
                          })}
                        </Select>
                      )}
                    </FormItem>
                    <FormItem {...formItemLayout} label={messages('request.key139'/*开户账号*/)}>
                      {getFieldDecorator('acceptAccount', {
                        rules: [{
                          required: companyBankOption.length > 0 ? true : false,
                          message: messages('common.please.select')
                        }]
                      })(
                        <Select placeholder={messages('common.please.select')}
                                showSearch
                                allowClear
                                onChange={this.handleChangeAcceptAccount}
                                getPopupContainer={() => document.getElementsByClassName('accept-account-container')[0]}
                                notFoundContent={bankSpin ? <Spin size="small"/> : messages('request.key145'/*无匹配结果*/)}>
                          {
                            companyBankOption.map(option => {
                              return <Option key={option.bankAccountNumber}>{option.bankAccountNumber}</Option>
                            })
                          }
                        </Select>
                      )}
                    </FormItem>
                  </div>
                )
              }
              <FormItem {...formItemLayout} label={messages('request.key140'/*开户银行*/)}>
                {getFieldDecorator('acceptBankName', {
                  initialValue: acceptBankName
                })(
                  <Input disabled/>
                )}
              </FormItem>
            </div>
          )}
          <div className="slide-footer">
            <Button type="primary" htmlType="submit" loading={loading}>
              {loanRefund ? messages('request.key146'/*确认*/) : messages('request.key147'/*通知财务已还款*/)}
            </Button>
            <Button onClick={this.handleCancel}>{messages('common.cancel')}</Button>
          </div>
        </Form>
      </div>
    )
  }
}

function mapStateToProps(state) {
  return {
    profile: state.login.profile,
    isOldCompany: state.login.isOldCompany
  }
}

const wrappedNewPaymentFrame = Form.create()(NewPaymentFrame);

export default connect(mapStateToProps)(wrappedNewPaymentFrame)
